package com.laolang.shop.modules.auth.util;

import com.laolang.shop.modules.auth.entity.TokenUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@UtilityClass
public class SecurityUtil {

    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public TokenUser getTokenUser() {
        Authentication authentication = getAuthentication();
        if (null == authentication) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof TokenUser) {
            return (TokenUser) principal;
        }
        return null;
    }

    public Long getUserId() {
        TokenUser tokenUser = getTokenUser();
        return null == tokenUser ? null : tokenUser.getUserId();
    }

    public Long getTenantId() {
        TokenUser tokenUser = getTokenUser();
        return null == tokenUser ? null : tokenUser.getTenantId();
    }
}
